package cn.scw.common.utils.pay;

import cn.scw.common.utils.DateUtils;
import cn.scw.common.utils.ServletUtils;
import cn.scw.common.utils.ip.IpUtils;
import cn.scw.framework.web.domain.AjaxResult;
import cn.scw.framework.web.domain.server.Sys;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.apache.commons.collections.map.HashedMap;
import org.jdom.JDOMException;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @description:
 * @author: lj
 * @create: 2020-06-05
 **/
public class PayUtils {


    public static AjaxResult pay(String body,String orderNumber,double totalPrice,String openId,String notifyUrl,boolean isNeedShare) throws JDOMException, IOException {
        // 商户号
        String mchId = ConfigUtil.MCH_ID;
        // API密钥
        String apiKey = ConfigUtil.API_KEY;

        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        //获取用户openID(JSAPI支付必须传openid)
//        String notify_url = "https://opapp.xyoume.com/api/payment/notify";//回调接口
        String trade_type = "JSAPI";// 交易类型H5支付 也可以是小程序支付参数
        SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
        ConfigUtil.commonParams(packageParams,mchId);
        packageParams.put("body", body);// 商品描述
        packageParams.put("out_trade_no", orderNumber);// 商户订单号
        packageParams.put("total_fee", String.valueOf(new BigDecimal(totalPrice).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).intValue()));// 总金额
        packageParams.put("spbill_create_ip", ip/*AddressUtils.getRealAddressByIP(ip)*/);// 发起人IP地址
        packageParams.put("notify_url", notifyUrl);// 回调地址
        packageParams.put("trade_type", trade_type);// 交易类型
        packageParams.put("openid", openId);//用户openID
        if(isNeedShare){
            packageParams.put("profit_sharing", "Y");//是否需要分账。后期可支持配置，根据需要来判断是否需要分账
        }
        System.out.println("pay total_fee=" + packageParams.get("total_fee").toString());
        String sign = PayCommonUtil.createSign("UTF-8", packageParams, apiKey);
        packageParams.put("sign", sign);// 签名
        String requestXML = PayCommonUtil.getRequestXml(packageParams);
        String resXml = WXHttpUtil.postData(ConfigUtil.UNIFIED_ORDER_URL, requestXML);
        Map map = XMLUtil.doXMLParse(resXml);
        String returnCode = (String) map.get("return_code");
        String returnMsg = (String) map.get("return_msg");
        StringBuffer url = new StringBuffer();
        if ("SUCCESS".equals(returnCode)) {
            String resultCode = (String) map.get("result_code");
            String errCodeDes = (String) map.get("err_code_des");
            if ("SUCCESS".equals(resultCode)) {
                //获取预支付交易会话标识
                String prepay_id = (String) map.get("prepay_id");
                String prepay_id2 = "prepay_id=" + prepay_id;
                String packages = prepay_id2;
                SortedMap<Object, Object> finalpackage = new TreeMap<Object, Object>();
                String timestamp = DateUtils.getTimestamp();
                String nonceStr = packageParams.get("nonce_str").toString();
                finalpackage.put("appId", ConfigUtil.APP_ID);
                finalpackage.put("timeStamp", timestamp);
                finalpackage.put("nonceStr", nonceStr);
                finalpackage.put("package", packages);
                finalpackage.put("signType", "MD5");
                //这里很重要  参数一定要正确 狗日的腾讯 参数到这里就成大写了
                //可能报错信息(支付验证签名失败 get_brand_wcpay_request:fail)
                sign = PayCommonUtil.createSign("UTF-8", finalpackage, apiKey);
                finalpackage.put("paySign", sign);
                // 支付时间

                return AjaxResult.success(finalpackage);
            } else {
                //  url.append("redirect:/weixinMobile/error?code=0&orderNo="+orderNumber);//该订单已支付
                return AjaxResult.error(errCodeDes);
            }
        } else {
            // url.append("redirect:/weixinMobile/error?code=1&orderNo="+orderNumber);//系统错误
            return AjaxResult.error(returnMsg);
        }
    }

    public static AjaxResult profitSharingAddReceiver(String userType,String userName,String openId) throws JDOMException, IOException {
        // 商户号
        String mchId = ConfigUtil.MCH_ID;
        // API密钥
        String apiKey = ConfigUtil.API_KEY;

        //String ip = IpUtils.getIpAddr(ServletUtils.getRequest());

        Map<String, Object> m = new HashedMap();
        //1.参数封装
        SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
        ConfigUtil.commonParams(packageParams,mchId);

        String sign = PayCommonUtil.createSign("UTF-8", packageParams, apiKey);
        packageParams.put("sign", sign);// 签名
        packageParams.put("sign_type", "HMAC-SHA256");
        SortedMap<Object, Object> receiver = new TreeMap<Object, Object>();
        //分账接收方类型：MERCHANT_ID：商户号（mch_id或者sub_mch_id）PERSONAL_OPENID：个人openid
        receiver.put("type", userType);
        receiver.put("account", openId);
        receiver.put("relation_type", "PARTNER");
        //否
//        receiver.put("name", "名字");
        receiver.put("relation_type", userName);
        //自定义分账关系
//        receiver.put("custom_relation", WechatConstants.USER);
        packageParams.put("receiver", JSON.toJSONString(receiver));

        String requestXML = null;
        try {
             requestXML = WXPayUtil.generateSignedXml((Map)packageParams, ConfigUtil.API_KEY, WXPayConstants.SignType.HMACSHA256);
        } catch (Exception e) {
            e.printStackTrace();
        }

     /*   String requestXML =   "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"
+"<xml>"
+"<nonce_str>1653439360</nonce_str>"
+"<receiver>{\"type\":\"PERSONAL_OPENID\",\"account\":\"ovpTY5dD5AVPimMkBUsDKw4IoG2U\",\"relation_type\":\"李腾杰\"}</receiver>"
+"<appid>wxc92e328fe669df24</appid>"
+"<sign>6B328C9403050A9DE5C595112B2968C615BEC5C4C0134117A857255866719DE5</sign>"
+"<mch_id>1510472101</mch_id>"
+"<sign_type>HMAC-SHA256</sign_type>"
+"</xml>";*/
        System.out.println("请求的参数：" + requestXML);
        String resXml = WXHttpUtil.postData(ConfigUtil.PROFIT_SHARING_ADD_RECEIVER, requestXML);
        System.out.println("返回报文：" + resXml);
        Map map = XMLUtil.doXMLParse(resXml);
        String returnCode = (String) map.get("return_code");
        String returnMsg = (String) map.get("return_msg");
        StringBuffer url = new StringBuffer();
        if ("SUCCESS".equals(returnCode)) {
            String resultCode = (String) map.get("result_code");
            String errCodeDes = (String) map.get("err_code_des");
            if ("SUCCESS".equals(resultCode)) {
                //获取预支付交易会话标识

                String mch_id = (String)map.get("mch_id");
                String appid = (String)map.get("appid");
                String retrunReceiver = (String)map.get("receiver");
                String nonce_str1 = (String)map.get("nonce_str");
                String retrunSign = (String)map.get("sign");
                String type = null;
                String account = null;
                String relation_type = null;
                JSONObject rs = JSONObject.parseObject(retrunReceiver);
                if (rs != null) {
                     type = rs.getString("type");
                     account = rs.getString("account");
                     relation_type = rs.getString("relation_type");
                }

                String prepay_id = (String) map.get("prepay_id");
                String prepay_id2 = "prepay_id=" + prepay_id;
                String packages = prepay_id2;
                SortedMap<Object, Object> finalpackage = new TreeMap<Object, Object>();
                String timestamp = DateUtils.getTimestamp();
                String nonceStr = packageParams.get("nonce_str").toString();
                finalpackage.put("type", type);
                finalpackage.put("account", account);
                finalpackage.put("relation_type", relation_type);
                // 支付时间

                return AjaxResult.success(finalpackage);
            } else {
                //  url.append("redirect:/weixinMobile/error?code=0&orderNo="+orderNumber);//该订单已支付
                return AjaxResult.error(errCodeDes);
            }
        } else {
            // url.append("redirect:/weixinMobile/error?code=1&orderNo="+orderNumber);//系统错误
            return AjaxResult.error(returnMsg);
        }
    }

    /**
     * @function 删除分账账号
     * @auther   litengjie
     */

    public static AjaxResult profitSharingDeleteReceiver(String userType,String userName,String openId) throws JDOMException, IOException  {
        // 商户号
        String mchId = ConfigUtil.MCH_ID;
        // API密钥
        String apiKey = ConfigUtil.API_KEY;

        Map<String,Map<String, String>> result = new HashMap<>();
        String currTime = PayCommonUtil.getCurrTime();
        String strTime = currTime.substring(8, currTime.length());
        String strRandom = PayCommonUtil.buildRandom(4) + "";
        String nonce_str = strTime + strRandom;
        Map<String, Object> m = new HashedMap();
        //1.参数封装
        SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
        ConfigUtil.commonParams(packageParams,mchId);

        String sign = PayCommonUtil.createSign("UTF-8", packageParams, apiKey);
        packageParams.put("sign", sign);// 签名
        //签名类型，目前只支持HMAC-SHA256
        packageParams.put("sign_type", "HMAC-SHA256");
        Map receiver = new HashedMap();
        //分账接收方类型：MERCHANT_ID：商户号（mch_id或者sub_mch_id）PERSONAL_OPENID：个人openid
        receiver.put("type", userType);
        receiver.put("account", openId);
        //否
//        receiver.put("name", "名字");
        receiver.put("relation_type", userName);
        //自定义分账关系
//        receiver.put("custom_relation", WechatConstants.USER);
        packageParams.put("receiver", JSON.toJSONString(receiver));
        String xmlParam = null;
        try {
             xmlParam = WXPayUtil.generateSignedXml((Map) packageParams, ConfigUtil.API_KEY, WXPayConstants.SignType.HMACSHA256);
        } catch (Exception e) {
                e.printStackTrace();
        }
            System.out.println("请求的参数：" + xmlParam);
            //xmlParam = new String(xmlParam.getBytes("UTF-8"), "ISO8859-1");
            //2.发送请求
            String xmlResult = WXHttpUtil.postData(ConfigUtil.PROFIT_SHARING_REMOVE_RECEIVER, xmlParam);

        Map map = XMLUtil.doXMLParse(xmlResult);
        String returnCode = (String) map.get("return_code");
        String returnMsg = (String) map.get("return_msg");
        StringBuffer url = new StringBuffer();
        if ("SUCCESS".equals(returnCode)) {
            String resultCode = (String) map.get("result_code");
            String errCodeDes = (String) map.get("err_code_des");
            if ("SUCCESS".equals(resultCode)) {
                //获取预支付交易会话标识
                String mch_id = (String)map.get("mch_id");
                String appid = (String)map.get("appid");
                String retrunReceiver = (String)map.get("receiver");
                String nonce_str1 = (String)map.get("nonce_str");
                String retrunSign = (String)map.get("sign");
                String type = null;
                String account = null;
                String relation_type = null;
                JSONObject rs = JSONObject.parseObject(retrunReceiver);
                if (rs != null) {
                    type = rs.getString("type");
                    account = rs.getString("account");
                    relation_type = rs.getString("relation_type");
                }

                String prepay_id = (String) map.get("prepay_id");
                String prepay_id2 = "prepay_id=" + prepay_id;
                String packages = prepay_id2;
                SortedMap<Object, Object> finalpackage = new TreeMap<Object, Object>();
                String timestamp = DateUtils.getTimestamp();
                String nonceStr = packageParams.get("nonce_str").toString();
                finalpackage.put("type", type);
                finalpackage.put("account", account);
                finalpackage.put("relation_type", relation_type);
                // 支付时间

                return AjaxResult.success(finalpackage);
            } else {
                //  url.append("redirect:/weixinMobile/error?code=0&orderNo="+orderNumber);//该订单已支付
                return AjaxResult.error(errCodeDes);
            }
        } else {
            // url.append("redirect:/weixinMobile/error?code=1&orderNo="+orderNumber);//系统错误
            return AjaxResult.error(returnMsg);
        }
    }

}
